package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

@WebServlet("/S01.do")
public class S01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = "";
        if (ServletFileUpload.isMultipartContent(req)){
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                List<FileItem> list = servletFileUpload.parseRequest(req);
                for (FileItem f : list) {
                    if (f.isFormField()) {
                        /*System.out.println("属性名：" + f.getFieldName());
                        System.out.println("属性值：" + f.getString("UTF-8"));*/
                        req.setAttribute(f.getFieldName(),f.getString("UTF-8"));
                    }else {
                        /*System.out.println("属性名：" + f.getFieldName());
                        System.out.println("文件名：" + f.getName());*/
                        String name = f.getName();
                        String[] split = name.split("\\.");
                        String s = "D:\\temp01\\javaWeb_test01\\" + "." + split[split.length - 1];
                        f.write(new File(s));
                        req.setAttribute(f.getFieldName(),s);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            action = req.getParameter("action");
        }
        try {
            Method declaredMethod = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            declaredMethod.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
